package io.hepu.robotize.controller;

import io.hepu.robotize.IContext;
import io.hepu.robotize.dto.LoginPayload;
import io.hepu.robotize.http.HttpResponse;
import io.hepu.robotize.security.JwtToken;
import io.hepu.robotize.service.ISysService;
import io.hepu.robotize.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

@Api(tags = "登录管理")
@RestController
public class LoginController {
    private static final Logger LOG = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private ISysService sysService;
    @Resource
    private IUserService userService;

    @Operation(summary = "手机登录", description = "返回登录结果")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "对象不存在", content = @Content)
    })
    @PostMapping("/auth/sms/{mobile}")
    public HttpResponse<JwtToken> smsAuth(@PathVariable("mobile") String mobile)
            throws Exception {
        String token = sysService.smsAuth(mobile, System.currentTimeMillis());
        LOG.info("SMS login successfully with token {} response", token);
        return HttpResponse.success(new JwtToken(token, IContext.getAuthzPlatform()));
    }

    @Operation(summary = "账号密码登录", description = "返回登录结果")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "请求成功"),
            @ApiResponse(responseCode = "403", description = "禁止访问"),
            @ApiResponse(responseCode = "404", description = "对象不存在", content = @Content)
    })
    @PostMapping("/auth/local")
    public HttpResponse<JwtToken> localAuth(@RequestBody LoginPayload user, HttpServletResponse response) throws Exception {
        String token = sysService.localAuth(user.getName(), user.getPassword(), System.currentTimeMillis());
        LOG.info("LOCAL login successfully with token {} response", token);
        response.setHeader("Authorization", token);
        return HttpResponse.success(new JwtToken(token, IContext.getAuthzPlatform()));
    }

}
